package rpcserver

import (
	corev1 "gluenet/internal/agent/api/core/v1"
	"gluenet/internal/agent/depend"
	"gluenet/internal/agent/driver/rpcserver"

	rpcv1 "gluenet/internal/agent/api/rpc/v1"
	"gluenet/internal/agent/service/helmsvc"
)

const (
	helm = rpcv1.RPC_SERVICE_HELM
)

func init() {
	depend.Provide(NewHelmRouter)
	registerRouter(helm, func(c rpcserver.IRoutes) {
		depend.Invoke(func(d *helmRouter) {
			d.initRouter(c)
		})
	})
}

type helmRouter struct {
	helm *helmsvc.Service
}

func NewHelmRouter(svc *helmsvc.Service) *helmRouter {
	return &helmRouter{svc}
}

func (r *helmRouter) initRouter(c rpcserver.IRoutes) {
	c.Group(rpcv1.HELM_RELEASE_RESOURCE).
		Func(`create`, r.createRelase).
		Func(`get`, r.getRelease).
		Func(`delete`, r.deleteRelease)
}

func (r *helmRouter) createRelase(c *rpcserver.Context) {
	release := new(corev1.HelmRelease)
	if err := c.BindJSON(release); err != nil {
		return
	}

	result := r.helm.CreateHelmRelease(release)
	c.JSON(result)
}

func (r *helmRouter) deleteRelease(c *rpcserver.Context) {
	meta := new(corev1.GluenetMeta)
	if err := c.BindJSON(meta); err != nil {
		return
	}

	result := r.helm.DeleteHelmRelease(meta)
	c.JSON(result)
}

func (r *helmRouter) getRelease(c *rpcserver.Context) {
	meta := new(corev1.GluenetMeta)
	if err := c.BindJSON(meta); err != nil {
		return
	}

	result := r.helm.GetHelmRelease(meta)
	c.JSON(result)
}
